package com.cplatform.movie.back.order.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cplatform.dbhelp.DbHelper;
import com.cplatform.dbhelp.page.Page;
import com.cplatform.movie.back.model.SessionUser;
import com.cplatform.movie.back.order.dao.OrderItemLinkDao;
import com.cplatform.movie.back.order.entity.Order;
import com.cplatform.movie.back.order.entity.OrderItemLink;
import com.cplatform.movie.back.store.service.StoreService;

@Service
public class OrderItemLinkService {
	@Autowired
	private OrderItemLinkDao orderItemLinkDao;
	@Autowired
	private StoreService storeService;
	@Autowired
	private DbHelper dbHelper;

	/**
	 * @throws SQLException 
	 * @Title: 根据商户获取某商户的订单列表 
	 * <br>
	 * @param order
	 * @param page
	 * @param storeId
	 * @return    
	 * @throws
	 */
	public Page<OrderItemLink> list(OrderItemLink order, int page, HttpSession session) throws SQLException {

		StringBuilder sql = new StringBuilder();
		List<Object> params = new ArrayList<Object>();
		sql.append("select link.* from T_ORDER_ITEM_LINK link, T_SMALL_SHOP_ITEMS item");
		sql.append(" where link.ITEM_ID=item.id(+)");
		
		// -- 权限过滤, 管理员可以查看所有商户订单
		SessionUser sessionUser = (SessionUser) session.getAttribute(SessionUser.SESSION_USER_KEY);
		if(sessionUser.getId() != 0) {
			Long storeId = storeService.findStoreIdByUserCode(sessionUser.getId());
			sql.append(" and item.STORE_ID=?");
			params.add(storeId);
		}

		if (StringUtils.isNotBlank(order.getItemName())) {
			sql.append(" and item.NAME like '%").append(order.getItemName().trim()).append("%'");
		}

		if (StringUtils.isNotBlank(order.getCreateTime())) {
			sql.append(" and link.create_time>=?");
			params.add(order.getCreateTime() + "000000");
		}

		if (StringUtils.isNotBlank(order.getCreateEndTime())) {
			sql.append(" and link.create_time<=?");
			params.add(order.getCreateEndTime() + "235959");
		}
		
		sql.append(" order by link.id desc");

		return dbHelper.getPage(sql.toString(), OrderItemLink.class, page, Page.DEFAULT_PAGESIZE, params.toArray());
	}

}
